package com.zyh.utils;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @Author zyh
 * @Date 2024/8/9 9:35
 * @Description countDownLatch 减法计数器
 */

public class CountDownDemo1 {
    public static void main(String[] args) {
        //创建减法计数器
        CountDownLatch countDownLatch = new CountDownLatch(10);
        //创建线程任务
        Runnable task = new Runnable() {
            @Override
            public void run() {
                //模拟出教室时间
                try {
                    Thread.sleep(new Random().nextInt(21) + 10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "离开教室");
                countDownLatch.countDown();
            }
        };
        //创建10个学生线程
        for (int i = 1; i <= 10; i++) {
            new Thread(task, "学生" + i).start();
        }
        //创建墙
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //创建门卫线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "关门");
            }
        }, "门卫").start();
    }
}
